//
//  MCXianLuXuanZeViewController.m
//  ZXZX
//
//  Created by MC on 2018/7/2.
//  Copyright © 2018年 TLYL01. All rights reserved.
//

#import "MCXianLuXuanZeViewController.h"
#import "MCGetIPAdress.h"


#define Top_MCXianLuXuanZe_HEIGHT  60

#define MCXianLuXuanZe_UnSelecteImageName @"XianLuXuanZe_UnSelecteImageName"
#define MCXianLuXuanZe_SelecteImageName @"XianLuXuanZe_SelecteImageName"

@interface MCXianLuXuanZeViewController ()<NSURLSessionDelegate>
@property (nonatomic,strong) NSMutableArray *arrLabel;
@property (nonatomic,strong) NSMutableArray *arrBtn;
@property (nonatomic, assign) int btnTag;
@end

@implementation MCXianLuXuanZeViewController

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    [self setProperty];
    [self setNav];
    [self xianLuView];
    [self setDefaultLine];
    
}

- (void)setDefaultLine{

    int btnTag = [[[NSUserDefaults standardUserDefaults] objectForKey:@"fastLineTag"] intValue];
    self.btnTag = btnTag;
    UIButton *btn = nil;
    if (btnTag != 0) {
         btn = self.arrBtn[btnTag -1001];
        [self btnFirClick:btn];
    }else{
        [[NSUserDefaults standardUserDefaults] setObject:SEVERBASEURL[0] forKey:@"BASEURL"];
        [self btnFirClick:nil];
    }
    
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden=NO;
    self.navigationController.navigationBar.translucent = NO;
    self.navigationController.navigationBar.barTintColor = RGB(31, 37, 69);

    if ([self respondsToSelector:@selector(edgesForExtendedLayout)])
    {
        self.edgesForExtendedLayout = UIRectEdgeNone;
    }
     [self loadData];
}


-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    self.navigationController.navigationBar.barTintColor = MC_THEME_COLOR;
}

- (void)setNavigationState:(BOOL)state{
    if (state) {
        self.edgesForExtendedLayout=UIRectEdgeBottom;
    }
    else{
        self.edgesForExtendedLayout=UIRectEdgeTop;
    }
    self.navigationController.navigationBar.translucent = YES;
    [self.navigationController setNavigationBarHidden:state animated:YES];
}

#pragma mark==================setProperty======================
-(void)setProperty{
    
    self.view.backgroundColor=RGB(31, 37, 69);
    self.navigationItem.title = @"线路检测中心";
    self.automaticallyAdjustsScrollViewInsets = NO;

    
}


-(void)createUIWithTag:(NSInteger)tag andSelectBtn:(UIButton *)SelectBtn andName:(NSString *)name andTimeLabel:(UILabel *)timeLab{
    
//    CGFloat
    SelectBtn.backgroundColor=[UIColor clearColor];
    SelectBtn.frame=CGRectMake(60, Top_MCXianLuXuanZe_HEIGHT+(tag-1001)*45, 25, 25);
    [self.view addSubview:SelectBtn];
    [SelectBtn setImage:[UIImage imageNamed:MCXianLuXuanZe_UnSelecteImageName] forState:UIControlStateNormal];
    [SelectBtn setImage:[UIImage imageNamed:MCXianLuXuanZe_SelecteImageName] forState:UIControlStateSelected];
    [SelectBtn addTarget:self action:@selector(btnFirClick:) forControlEvents:UIControlEventTouchUpInside];
    [SelectBtn setSelected:NO];
    SelectBtn.tag=tag;
    
    UILabel * lab_name = [[UILabel alloc]init];
    lab_name.frame=CGRectMake((G_SCREENWIDTH-65)/2.0, Top_MCXianLuXuanZe_HEIGHT+(tag-1001)*45, 65, 25);
    [self.view addSubview:lab_name];
    lab_name.text = name;
    lab_name.textColor = RGB(214, 220, 255);
    lab_name.font=[UIFont systemFontOfSize:15];
    
    
    timeLab.frame=CGRectMake(G_SCREENWIDTH-70, Top_MCXianLuXuanZe_HEIGHT+(tag-1001)*45, 90, 25);
    [self.view addSubview:timeLab];
    timeLab.text = @"--";
    timeLab.textColor = RGB(214, 220, 255);
    timeLab.font=[UIFont systemFontOfSize:15];
  

}


-(void)xianLuView{

    NSMutableArray *arrBtn = [NSMutableArray array];
    self.arrBtn = arrBtn;
    NSMutableArray *arrLabel = [NSMutableArray array];
    self.arrLabel = arrLabel;
    NSMutableArray *nameAry = [NSMutableArray array];
    NSArray *hzNumberArray = @[@"一",@"二",@"三",@"四",@"五",@"六",@"七",@"八",@"九",@"十"];
    for (NSInteger i=0; i<SEVERBASEURL.count; i++) {
        NSString *str = [NSString stringWithFormat:@"线路%@号",hzNumberArray[i]];
        [nameAry addObject:str];
    }
    
    for (NSInteger i =0; i<SEVERBASEURL.count; i++) {
        UIButton *SelectBtn = [[UIButton alloc]init];
        UILabel *timeLab = [[UILabel alloc]init];
        [arrBtn addObject:SelectBtn];
        [arrLabel addObject:timeLab];
        [self createUIWithTag:1001 + i andSelectBtn:SelectBtn andName:nameAry[i]  andTimeLabel:timeLab];
    }
    
    UIButton * selectedXianLu = [[UIButton alloc]init];
    [self.view addSubview:selectedXianLu];
    selectedXianLu.layer.cornerRadius = 22.5;
    selectedXianLu.layer.masksToBounds = YES;
    selectedXianLu.titleLabel.font = [UIFont systemFontOfSize:MC_REALVALUE(18)];
    [selectedXianLu addTarget:self action:@selector(selectedXianLuClick:) forControlEvents:UIControlEventTouchUpInside];
    [selectedXianLu setTitleColor:RGB(105, 52, 10) forState:UIControlStateNormal];
    [selectedXianLu setTitle:@"选择线路" forState:UIControlStateNormal];
    selectedXianLu.titleLabel.textColor = [UIColor whiteColor];
    selectedXianLu.titleLabel.font = [UIFont boldSystemFontOfSize:MC_REALVALUE(16)];
    selectedXianLu.frame=CGRectMake(38, G_SCREENHEIGHT-147-45, G_SCREENWIDTH-38*2, 45);
    [selectedXianLu setBackgroundImage:[UIImage imageNamed:@"BtnBackImgV"] forState:UIControlStateNormal];
    
    UILabel *label = [[UILabel alloc] init];
    label.textAlignment=NSTextAlignmentCenter;
    label.frame = CGRectMake(10, G_SCREENHEIGHT-123, G_SCREENWIDTH-10*2, 20);
    label.text = @"备用网址温馨提示：数字越小，APP访问速度越快。";
    label.font = [UIFont systemFontOfSize:10];
    label.textColor = [UIColor colorWithRed:93.0036/255.0 green:99.0012/255.0 blue:129.002/255.0 alpha:1];
    [self.view addSubview:label];
    
}


#pragma mark==================loadData======================
-(void)loadData{
    
    WS(wself);

    // 创建信号量
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
    // 创建全局并行
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_group_t group = dispatch_group_create();
    
    for (NSInteger i = 0; i<SEVERBASEURL.count; i++) {
        dispatch_group_async(group, queue, ^{
            NSString *urlStr = [NSString stringWithFormat:@"%@web-api/api/v4/test_line",SEVERBASEURL[i]];
            
            [wself loadXianLuWithUrl:urlStr andXianLutitleTag:i+1 secLabel:wself.arrLabel[i]  semaphore:semaphore];
        });
    }
    

    dispatch_group_notify(group, queue, ^{
        for (NSInteger i = 0; i<SEVERBASEURL.count; i++) {
            dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
        }

        dispatch_async(dispatch_get_main_queue(), ^{
           

        });
    });

}

-(void)setNav{
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setImage:[UIImage imageNamed:@"图层-6"] forState:UIControlStateNormal];
    [button setImage:[UIImage imageNamed:@"图层-6"] forState:UIControlStateHighlighted];
    [button setTitle:@"返回" forState:UIControlStateNormal];
    [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    button.size = CGSizeMake(90, 40);
    button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    button.contentEdgeInsets = UIEdgeInsetsMake(0, -7, 0, 0);
    [button addTarget:self action:@selector(disMissViewController) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button];
    self.hidesBottomBarWhenPushed = YES;
}

- (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential * _Nullable))completionHandler{
    
    
    
    SecTrustRef servertrust = challenge.protectionSpace.serverTrust;
    
    SecCertificateRef certi= SecTrustGetCertificateAtIndex(servertrust, 0);
    
    NSData *certidata = CFBridgingRelease(CFBridgingRetain(CFBridgingRelease(SecCertificateCopyData(certi))));
    
    NSString *path = [[NSBundle mainBundle] pathForResource:@"https" ofType:@"cer"];
    
    NSData *localCertiData = [NSData dataWithContentsOfFile:path];
    
    if ([certidata isEqualToData:localCertiData]) {
        
        NSURLCredential *credential = [[NSURLCredential alloc] initWithTrust:servertrust];
        
        [challenge.sender useCredential:credential forAuthenticationChallenge:challenge];
        
        completionHandler(NSURLSessionAuthChallengeUseCredential, credential);
        
        
        
    }else {
        
        completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, nil);
        
       
        
    }
    
    
    
}

#pragma mark ------------ test------end-------------------------
- (void)loadXianLuWithUrl:(NSString *)urlStr andXianLutitleTag:(NSInteger )tag secLabel:(UILabel *)secLabel  semaphore:(dispatch_semaphore_t)semaphore{
    
    NSURL *url=[NSURL URLWithString: urlStr];
    NSURLSession *session=[NSURLSession sharedSession];
     [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[[NSOperationQueue alloc]init]];
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];
    request.HTTPMethod = @"GET";
    NSString *uuid = [UIDevice currentDevice].identifierForVendor.UUIDString;
    NSString *ip =  [MCGetIPAdress getIPAddress:YES];
    [request addValue:uuid forHTTPHeaderField:@"X-APP-CID"];
    [request addValue:[NSString getAgentInfo] forHTTPHeaderField:@"X-APP-AGENT"];
    [request addValue:@"JAVAAPI" forHTTPHeaderField:@"X-PROTOCOL"];
    [request addValue:ip forHTTPHeaderField:@"X-APP-IP"];
    
   
    NSTimeInterval intervalS = [[NSDate date] timeIntervalSince1970] * 1000;
    NSURLSessionDataTask *dataTask=[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        dispatch_semaphore_signal(semaphore);
        NSTimeInterval intervalE = [[NSDate date] timeIntervalSince1970] * 1000;
        NSHTTPURLResponse *re = (NSHTTPURLResponse *)response;
        dispatch_async(dispatch_get_main_queue(), ^{
            
          
            if (re.statusCode == 200) {
                int testTime = (intervalE - intervalS)/30;
                if ( testTime < 20 ) {
                    secLabel.textColor = [UIColor greenColor];
                    //表示响应较快，用绿色系表示。
                }else if( testTime >=20 && testTime < 100 ){
                    secLabel.textColor =  [UIColor yellowColor];
                    //表示响应较慢，用黄色系表示。
                }else{
                    secLabel.textColor = [UIColor redColor];
                    //表示响应很慢，用红色系表示。
                }
                secLabel.text =  [NSString stringWithFormat:@"%dms",testTime];
            } else {
                secLabel.textColor = RGB(185, 86, 86);
                secLabel.text = @"超时";

            }
        });
        
    } ];
    [dataTask resume];
 
    
}

/*
 * 选择某一个线路
 */

- (void)btnFirClick:(UIButton *)btn{
    //默认线路
    if (btn==nil) {
        if ([testApi isEqualToString:@"testApi"]) {
            UIButton *defaultBtn = self.arrBtn[0];
            defaultBtn.selected = YES;
            return;
        }else{
            for (NSInteger i = 0; i<SEVERBASEURL.count; i++) {
                NSString *url = SEVERBASEURL[i];
                
                if ([DEFAULTSEVERBASEURL isEqualToString:url]) {
                    UIButton *defaultBtn = self.arrBtn[i];
                    defaultBtn.selected = YES;
                    return;
                }
            }
        }
        
        
 
    }
    
    int i = 0;
    for (UIButton *btnselected in self.arrBtn) {
        
        if (btnselected == btn) {
            btnselected.selected = YES;
            self.btnTag = (int)btn.tag;
           
        }else{
            btnselected.selected = NO;
        }
        i++;
    }

    [[NSUserDefaults standardUserDefaults] setObject:@(btn.tag) forKey:@"fastLineTag"];
}


-(void)disMissViewController{
    [self dismissViewControllerAnimated:NO completion:nil];
}
#pragma mark-线路选择
-(void)selectedXianLuClick:(UIButton *)btn{
    if (self.btnTag == 0) {
        [[NSUserDefaults standardUserDefaults] setObject:SEVERBASEURL[0] forKey:@"BASEURL"];
    } else {
        [[NSUserDefaults standardUserDefaults] setObject:SEVERBASEURL[self.btnTag - 1001] forKey:@"BASEURL"];
    }
    
    [self disMissViewController];
}

-(void)setBtnImgVSelected:(BOOL)selected andBtn:(UIButton *)SelectBtn {
    [SelectBtn setImage:[UIImage imageNamed:MCXianLuXuanZe_UnSelecteImageName] forState:UIControlStateNormal];

    
}


@end
